import os
import re
import sys

def normalize_name(name):
    """规范化名称：去除首尾空格，确保名称有效性"""
    name = name.strip()
    if not name:
        raise ValueError("名称不能为空")
    if not name.isidentifier():
        raise ValueError("名称必须是有效的标识符")
    return name

def process_filename(filename, name, name_lower, name_upper):
    """处理文件名中的替换"""
    new_filename = filename
    
    # 替换所有大小写变体
    new_filename = new_filename.replace('xxx', name_lower)
    new_filename = new_filename.replace('XXX', name_upper)
    new_filename = new_filename.replace('Xxx', name.title())  # 首字母大写
    
    # 使用正则表达式进行更灵活的匹配
    new_filename = re.sub(r'(?i)xxx', lambda m: name_upper if m.group().isupper() else name_lower, new_filename)
    
    return new_filename

def process_file_content(content, name, name_lower, name_upper):
    """处理文件内容中的替换"""
    new_content = content
    
    # 基础替换
    new_content = new_content.replace('xxx', name_lower)
    new_content = new_content.replace('XXX', name_upper)
    new_content = new_content.replace('Xxx', name.title())
    
    # 使用正则表达式进行智能大小写匹配
    def replace_match(match):
        original = match.group()
        if original.isupper():
            return name_upper
        elif original.istitle():
            return name.title()
        else:
            return name_lower
    
    # 匹配各种大小写变体
    new_content = re.sub(r'(?i)xxx', replace_match, new_content)
    
    return new_content

def replace_in_files(name):
    """主替换函数"""
    # 规范化名称
    name_normalized = normalize_name(name)
    name_lower = name_normalized.lower()  # 小写化
    name_upper = name_normalized.upper()  # 大写化
    
    print(f"规范化后的名称: {name_normalized}")
    print(f"小写形式: {name_lower}")
    print(f"大写形式: {name_upper}")
    
    # 获取当前工作目录
    current_dir = os.getcwd()
    
    # 统计信息
    files_renamed = 0
    files_updated = 0
    total_changes = 0
    
    # 遍历当前目录下的所有文件
    for filename in os.listdir(current_dir):
        file_path = os.path.join(current_dir, filename)
        
        # 只处理.c和.h文件
        if filename.endswith(('.c', '.h')):
            print(f"\n处理文件: {filename}")
            
            # 处理文件名中的替换
            new_filename = process_filename(filename, name_normalized, name_lower, name_upper)
            
            if new_filename != filename:
                new_file_path = os.path.join(current_dir, new_filename)
                
                # 检查目标文件是否已存在
                if os.path.exists(new_file_path) and new_file_path != file_path:
                    print(f"警告: 目标文件 {new_filename} 已存在，跳过重命名")
                else:
                    os.rename(file_path, new_file_path)
                    print(f"✓ 重命名文件: {filename} -> {new_filename}")
                    files_renamed += 1
                    file_path = new_file_path  # 更新文件路径为新文件名
            
            # 处理文件内容中的替换
            try:
                with open(file_path, 'r', encoding='utf-8') as file:
                    content = file.read()
                
                # 替换内容
                original_content = content
                new_content = process_file_content(content, name_normalized, name_lower, name_upper)
                
                # 如果内容有变化，则写回文件
                if new_content != original_content:
                    # 计算更改数量
                    changes = sum(1 for i in range(len(original_content)) 
                                 if original_content[i:i+3].lower() == 'xxx' and 
                                 new_content[i:i+len(name_normalized)] != original_content[i:i+3])
                    
                    with open(file_path, 'w', encoding='utf-8') as file:
                        file.write(new_content)
                    
                    print(f"✓ 更新文件内容: {changes} 处替换")
                    files_updated += 1
                    total_changes += changes
                    
            except UnicodeDecodeError:
                print(f"警告: 文件 {os.path.basename(file_path)} 编码不支持，跳过内容处理")
            except Exception as e:
                print(f"错误: 处理文件 {os.path.basename(file_path)} 时出错: {e}")
    
    # 输出统计信息
    print(f"\n{'='*50}")
    print(f"操作完成统计:")
    print(f"重命名文件: {files_renamed} 个")
    print(f"更新文件内容: {files_updated} 个")
    print(f"总替换次数: {total_changes} 次")
    print(f"{'='*50}")
    
    return files_renamed + files_updated > 0  # 返回是否有更改发生

def preview_changes(name):
    """预览将要进行的更改"""
    name_normalized = normalize_name(name)
    name_lower = name_normalized.lower()
    name_upper = name_normalized.upper()
    
    current_dir = os.getcwd()
    changes_found = False
    
    print(f"\n预览更改 (不会实际修改文件):")
    print(f"搜索模式: 'xxx' -> '{name_lower}'")
    print(f"搜索模式: 'XXX' -> '{name_upper}'")
    print(f"{'-'*40}")
    
    for filename in os.listdir(current_dir):
        if filename.endswith(('.c', '.h')):
            # 检查文件名更改
            new_filename = process_filename(filename, name_normalized, name_lower, name_upper)
            if new_filename != filename:
                print(f"文件名: {filename} -> {new_filename}")
                changes_found = True
            
            # 检查文件内容更改
            try:
                with open(os.path.join(current_dir, filename), 'r', encoding='utf-8') as file:
                    content = file.read()
                
                new_content = process_file_content(content, name_normalized, name_lower, name_upper)
                if new_content != content:
                    changes_count = content.count('xxx') + content.count('XXX') + content.count('Xxx')
                    print(f"文件内容: {filename} ({changes_count} 处需要替换)")
                    changes_found = True
                    
            except:
                pass
    
    if not changes_found:
        print("未找到需要替换的内容")
    
    return changes_found

def wait_for_exit():
    """等待用户按键退出"""
    print("\n" + "="*50)
    if getattr(sys, 'frozen', False):
        # 如果是打包后的exe文件
        input("程序执行完成，按回车键退出...")
    else:
        # 如果是Python脚本
        input("按回车键退出...")

def main():
    try:
        # 获取用户输入
        name = input("请输入器件名称: ").strip()
        
        # 规范化名称
        name_normalized = normalize_name(name)
        
        # 预览更改
        changes_exist = preview_changes(name_normalized)
        
        if not changes_exist:
            print("\n没有找到需要替换的内容。")
            wait_for_exit()
            return
        
        # 确认操作
        confirm = input("\n确认执行上述更改? (y/N): ").strip().lower()
        
        if confirm == 'y' or confirm == 'yes':
            changes_made = replace_in_files(name_normalized)
            if not changes_made:
                print("没有进行任何更改。")
        else:
            print("操作已取消")
            
        wait_for_exit()
            
    except ValueError as e:
        print(f"输入错误: {e}")
        wait_for_exit()
    except KeyboardInterrupt:
        print("\n程序被用户中断")
        wait_for_exit()
    except Exception as e:
        print(f"程序执行出错: {e}")
        wait_for_exit()

if __name__ == "__main__":
    print("文件替换工具 - 支持智能大小写匹配")
    print("=" * 50)
    main()